package com.dhcc.bpm.business.papc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.business.papc.entity.BatchRecord;
import com.dhcc.bpm.business.papc.entity.BatchSchedule;
import com.dhcc.bpm.business.papc.service.IBatchRecordService;
import com.dhcc.bpm.business.papc.service.IBatchScheduleService;
import com.dhcc.bpm.business.papc.vo.BatchRecordVO;
import com.dhcc.bpm.business.papc.vo.CountRightChartVo;
import com.dhcc.bpm.business.papc.vo.StaticVo;
import com.dhcc.bpm.common.utils.StringUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 批量任务记录表  控制器
 *
 * @author zhanghang
 * @since 2020-12-18
 */
@RestController
@AllArgsConstructor
@RequestMapping("bpm-papc/batchrecord")
@Api(value = "批量任务记录表 ", tags = "批量任务记录表 接口")
public class BatchRecordController extends BladeController {

    private IBatchRecordService batchRecordService;
    private IBatchScheduleService batchScheduleService;

    /**
     * 分页 批量任务记录表
     */
    @GetMapping("/detailsPage")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入batchRecord")
    public R<IPage<BatchRecord>> detailsPage(BatchRecord batchRecord, Query query) {
        String taskDesc = "";
        if (StringUtils.isNotBlank(batchRecord.getTaskDesc())) {
            taskDesc = batchRecord.getTaskDesc();
            batchRecord.setTaskDesc(null);
        }
        QueryWrapper<BatchRecord> queryWrapper = Condition.getQueryWrapper(batchRecord);
        if (StringUtils.isNotBlank(taskDesc)) {
            queryWrapper.likeRight("TASK_DESC", taskDesc);
        }
        IPage<BatchRecord> pages = batchRecordService.page(Condition.getPage(query), queryWrapper);
        return R.data(pages);
    }

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入batchRecord")
    public R<BatchRecord> detail(BatchRecord batchRecord) {
        BatchRecord detail = batchRecordService.getOne(Condition.getQueryWrapper(batchRecord));
        return R.data(detail);
    }

    /**
     * 分页 批量任务记录表
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入batchRecord")
    public R<IPage<BatchRecord>> list(BatchRecord batchRecord, Query query) {
        IPage<BatchRecord> pages = batchRecordService.page(Condition.getPage(query), Condition.getQueryWrapper(batchRecord));
        return R.data(pages);
    }

    /**
     * 自定义分页 批量任务记录表
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入batchRecord")
    public R<IPage<BatchRecord>> page(BatchRecordVO batchRecord, Query query) {
//		IPage<BatchRecordVO> pages = batchRecordService.selectBatchRecordPage(Condition.getPage(query), batchRecord);
        QueryWrapper<BatchRecord> wrapper = new QueryWrapper<>();
        wrapper.select("ID", "TASK_BUSI_DATE", "PRDT_CODE", "PK_TASK_NO", "TASK_TYPE", "PK_TASK_NAME", "SEND_MODE", "ZJYW_TASK_STS", "MANUAL_LAB", "ORDER_NO", "TASK_OPEN", "ZJYW_SYS_DATE", "ZJYW_TASK_MSG",
                "NOW_NUM",
                "TASK_BATCH_NO",
                "ZJYW_NOW_TRACE",
                "ZJYW_SYS_TIME",
                "ZJYW_SYS_END_TIME",
                "TASK_DESC",
                "PUL_ID","PK_TYPE", "BSNTPNO", "IP_ADDR","TASK_GROUP", "PID",
                "port","start_time","end_time","tx_code"
        );

        if (StringUtils.isNotBlank(batchRecord.getTaskType())) {
            wrapper.eq("TASK_TYPE", batchRecord.getTaskType());
        }
        if (StringUtils.isNotBlank(batchRecord.getPkTaskName())) {
            wrapper.likeRight("PK_TASK_NAME", batchRecord.getPkTaskName());
        }
        if (StringUtils.isNotBlank(batchRecord.getPkTaskNo())) {
            wrapper.likeRight("PK_TASK_NO", batchRecord.getPkTaskNo());
        }
        if (StringUtils.isNotBlank(batchRecord.getZjywTaskSts())) {
            wrapper.likeRight("ZJYW_TASK_STS", batchRecord.getZjywTaskSts());
        } if (StringUtils.isNotBlank(batchRecord.getSendMode())) {
            wrapper.likeRight("SEND_MODE", batchRecord.getSendMode());
        }
        if (StringUtils.isNotBlank(batchRecord.getBusinessBeginDate()) && StringUtils.isNotBlank(batchRecord.getBusinessEndDate())) {
            wrapper.between("TASK_BUSI_DATE", batchRecord.getBusinessBeginDate(), batchRecord.getBusinessEndDate());
        }

        if (StringUtils.isNotBlank(batchRecord.getExecutionBeginDate()) && StringUtils.isNotBlank(batchRecord.getExecutionEndDate())) {
            wrapper.between("ZJYW_SYS_DATE", batchRecord.getExecutionBeginDate(), batchRecord.getExecutionEndDate());
        }
//		wrapper.groupBy("TASK_BUSI_DATE", "PRDT_CODE", "PK_TASK_NO", "ORDER_NO");
        wrapper.groupBy("ID", "TASK_BUSI_DATE", "PRDT_CODE", "PK_TASK_NO", "TASK_TYPE",
                "PK_TASK_NAME", "SEND_MODE", "ZJYW_TASK_STS", "MANUAL_LAB", "ORDER_NO",
                "TASK_OPEN", "ZJYW_SYS_DATE", "ZJYW_TASK_MSG",
                "NOW_NUM",
                "TASK_BATCH_NO",
                "ZJYW_NOW_TRACE",
                "ZJYW_SYS_TIME",
                "ZJYW_SYS_END_TIME",
                "TASK_DESC",
                "PUL_ID","PK_TYPE", "BSNTPNO", "IP_ADDR","TASK_GROUP", "PID",
                "port","start_time","end_time","tx_code"
        );
        wrapper.orderByAsc("TASK_BUSI_DATE", "PRDT_CODE", "PK_TASK_NO", "ORDER_NO");
        IPage<BatchRecord> pages = batchRecordService.page(Condition.getPage(query), wrapper);
        return R.data(pages);
    }

    /**
     * 新增 批量任务记录表
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入batchRecord")
    public R<Boolean> save(@Valid @RequestBody BatchRecord batchRecord) {
        return R.status(batchRecordService.save(batchRecord));
    }

    /**
     * 修改 批量任务记录表
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入batchRecord")
    public R<Boolean> update(@Valid @RequestBody BatchRecord batchRecord) {
        return R.status(batchRecordService.updateById(batchRecord));
    }

    /**
     * 新增或修改 批量任务记录表
     */
    @PostMapping("/submit")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入batchRecord")
    public R<Boolean> submit(@Valid @RequestBody BatchRecord batchRecord) {
        return R.status(batchRecordService.saveOrUpdate(batchRecord));
    }


    /**
     * 删除 批量任务记录表
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "删除", notes = "传入ids")
    public R<Boolean> remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return R.status(batchRecordService.removeByIds(Func.toLongList(ids)));
    }

    /**
     * 详情
     */
    @GetMapping("/count")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入batchRecord")
    public R<Map<String, Integer>> count(BatchRecord batchRecord) {
        int totalTask = Math.toIntExact(batchScheduleService.count(new QueryWrapper<BatchSchedule>().isNotNull("PID")));
        // 查询总
        batchRecord.setZjywSysDate(LocalDate.now().format(DateTimeFormatter.ofPattern("YYYYMMdd")));
        Integer tatalCalls = batchRecordService.selectZjywBatchRecordByTotalCalls(batchRecord);
        int executiry = Math.toIntExact(batchRecordService.count(new QueryWrapper<BatchRecord>().eq("ZJYW_TASK_STS", "02")));
        Map<String, Integer> result = new HashMap<>();
        result.put("totalTask", totalTask);
        result.put("totalCalls", tatalCalls == null ? 0 : tatalCalls);
        result.put("executiry", executiry);
        return R.data(result);
    }


    /**
     * 日期折线图
     */
    @GetMapping("/countDate")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "日期折线图", notes = "不用传值")
    public R<List<StaticVo>> countDate(String begDate,String endDate) {
        List<Map<String, Object>> totalMap = batchRecordService.selectZjywBatchRecordGroupDates( begDate, endDate);
        BatchRecord batchRecord = new BatchRecord();
        batchRecord.setZjywTaskSts("02");//正在执行
        List<Map<String, Object>> map1;
        map1 = batchRecordService.selectZjywBatchRecordGroupDate(batchRecord);

        List<StaticVo> mapIng = getMaSts(map1, totalMap, "正在执行");

        batchRecord.setZjywTaskSts("03");//失败
        map1 = batchRecordService.selectZjywBatchRecordGroupDate(batchRecord);
        List<StaticVo> mapFail = getMaSts(map1, totalMap, "失败");


        batchRecord.setZjywTaskSts("00");//成功
        map1 = batchRecordService.selectZjywBatchRecordGroupDate(batchRecord);
        List<StaticVo> mapSucc = getMaSts(map1, totalMap, "成功");

        batchRecord.setZjywTaskSts("01");//未执行
        map1 = batchRecordService.selectZjywBatchRecordGroupDate(batchRecord);
        List<StaticVo> mapInit = getMaSts(map1, totalMap, "未执行");

        List<StaticVo> result = new ArrayList<>();
        result.addAll(mapIng);
        result.addAll(mapFail);
        result.addAll(mapSucc);
        result.addAll(mapInit);
        //排序  先按照时间排序，再按照count排序
        Collections.sort(result, (o1, o2) -> {

            int i = Integer.valueOf(o1.getTime()) - Integer.valueOf(o2.getTime());
            if (i == 0) {
                if (o1.getCount().subtract(o2.getCount()).toString().contains("-")) {
                    return -1;
                } else {
                    return 1;
                }
            }
            return i;
        });
        return R.data(result);
    }


    /**
     * @Author wangjinghan
     * @Description 返给页面的map
     * @param:
     * @return:
     * @date: 2021/3/5 17:16
     */
    public static List<StaticVo> getMaSts(List<Map<String, Object>> map1, List<Map<String, Object>> totalMap, String name) {
        List<StaticVo> mapIng = new ArrayList<>();//正在执行

        for (Map<String, Object> tMap : totalMap) {


            String date = (String) tMap.get("ZJYW_SYS_DATE");
            BigDecimal total = new BigDecimal("0");
            if (tMap.get("TOTALSUM") != null) {
                if (!"class java.math.BigDecimal".equals(tMap.get("TOTALSUM").getClass().toString())) {
                    //说明是Long类型----mysql数据库识别时
                    total = new BigDecimal((Long) tMap.get("TOTALSUM"));
                } else {//oracle数据库识别时
                    total = (BigDecimal) tMap.get("TOTALSUM");
                }
            }
            BigDecimal numB = new BigDecimal("0");
            for (int i = 0; i < map1.size(); i++) {
                Map<String, Object> map2 = map1.get(i);
                StaticVo staticVo = new StaticVo();
                staticVo.setTime(date);
                staticVo.setName(name);
                //取对应num
                if (map2.containsValue(date)) {
                    //存在这个日期的数据----------跳出循环
                    String num = String.valueOf(map2.get("NUM"));
                    numB = new BigDecimal(num);
                    staticVo.setCount(numB.divide(total, 2, BigDecimal.ROUND_HALF_UP));
                    mapIng.add(staticVo);
                    break;
                } else if (i == map1.size() - 1) {
                    //不存在这个日期的数据----------并且执行到最后一条了
                    staticVo.setCount(new BigDecimal("0.00"));
                    mapIng.add(staticVo);
                    break;
                }

            }

        }


        return mapIng;
    }

    /**
     * 日期百分比图
     */
    @GetMapping("/countRightChart")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "日期饼状图", notes = "不用传值")
    public R countRightChart() {

        BatchRecord batchRecord = new BatchRecord();
        batchRecord.setZjywSysDate(LocalDate.now().format(DateTimeFormatter.ofPattern("YYYYMMdd")));
        List<BatchRecord> list = batchRecordService.selectZjywBatchRecordList(batchRecord);
        int init = 0; //01
        int ing = 0; //02
        int ssuccess = 0;  //00
        int fail = 0;   //03
        if (list.size() == 0) {


            List<CountRightChartVo> list2 = new ArrayList();
//            CountRightChartVo countRightChartVo=new CountRightChartVo();
//            countRightChartVo.setCount(0D);
//            countRightChartVo.setItem("成功");
//            list2.add(countRightChartVo);
//            countRightChartVo.setItem("失败");
//            list2.add(countRightChartVo);
//            countRightChartVo.setItem("正在执行");
//            list2.add(countRightChartVo);
            return R.data(list2);

        }

        for (BatchRecord b : list) {
            switch (b.getZjywTaskSts()) {
                case "01":
                    ++init;
                    break;
                case "02":
                    ++ing;
                    break;
                case "00":
                    ++ssuccess;
                    break;
                case "03":
                    ++fail;
                    break;
                default:
                    break;
            }
        }
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
        List<CountRightChartVo> list2 = new ArrayList();
        CountRightChartVo countRightChartVo = new CountRightChartVo();
        double s1 = (double) ssuccess / list.size() * 100;
        countRightChartVo.setCount(Double.valueOf(df.format(s1)));
        countRightChartVo.setItem("成功");
        list2.add(countRightChartVo);

        double s2 = (double) fail / list.size() * 100;
        CountRightChartVo countRightChartVo2 = new CountRightChartVo();
        countRightChartVo2.setCount(Double.valueOf(df.format(s2)));
        countRightChartVo2.setItem("失败");
        list2.add(countRightChartVo2);

        double s3 = (double) ing / list.size() * 100;
        CountRightChartVo countRightChartVo3 = new CountRightChartVo();
        countRightChartVo3.setCount(Double.valueOf(df.format(s3)));
        countRightChartVo3.setItem("正在执行");
        list2.add(countRightChartVo3);

        double s4 = (double) init / list.size() * 100;
        CountRightChartVo countRightChartVo4 = new CountRightChartVo();
        countRightChartVo4.setCount(Double.valueOf(df.format(s4)));
        countRightChartVo4.setItem("未执行");
        list2.add(countRightChartVo4);
        return R.data(list2);
    }
}
